package com.hankol.community

import android.view.View
import androidx.fragment.app.Fragment
import com.alibaba.android.arouter.facade.annotation.Route
import com.baselibrary.BaseConstant
import com.baselibrary.Constants
import com.baselibrary.MessageBus
import com.baselibrary.activity.BaseActivity
import com.baselibrary.extension.checkNotNull
import com.baselibrary.extension.checkValue
import com.baselibrary.fragment.CommonDynamicFragment
import com.baselibrary.manager.SensorsDataManager
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.*
import com.baselibrary.view.share.SharePopupWindow
import com.flyco.tablayout.listener.OnTabSelectListener
import com.google.android.material.appbar.AppBarLayout
import com.hankol.community.arouter.CommunityHelp
import com.hankol.community.bean.ShowShare2Bean
import com.hankol.community.bean.TopicDetailsBean
import com.hankol.community.databinding.ActivityTopicDetailBinding
import com.hankol.community.viewmodel.CommunityViewModel
import java.util.*


/**
 *@author:hanke
 *2022/4/6
 *desc:话题详情页
 */
@Route(path = ActivityRouter.COMMUNITY.COMMUNITY_TOPIC_DETAIL)
class TopicDetailActivity : BaseActivity(), View.OnClickListener {
    private val titles = ArrayList<String>()
    private val fragments = ArrayList<Fragment>()
    private var topicId = ""
    private var topicName = ""
    private var topicSource = ""
    private lateinit var mDataBinding: ActivityTopicDetailBinding
    private lateinit var mViewModel: CommunityViewModel
    private var mTopicDetailsBean: TopicDetailsBean.DataBean? = null
    val communityHelp: CommunityHelp =
            ActivityRouter.getARouterInterface(ActivityRouter.COMMUNITY.COMMUNITY_HELP)
    private lateinit var hotFragment: CommonDynamicFragment
    private lateinit var latestFragment: CommonDynamicFragment
    private var mShowSharePop: SharePopupWindow? = null
    private var hasFocus = false;
    override fun getLayoutId(): Int {
        return R.layout.activity_topic_detail
    }

    override fun init() {
        setStatusBarHeight(R.color.color_FFFFFF)
        mDataBinding = getDataBinding<ActivityTopicDetailBinding>()
        mViewModel = getActivityViewModelProvider(this).get(CommunityViewModel::class.java)
        if (intent.extras!=null) {
            topicSource = ARouterUtils.parseParams(intent.extras!!, "tsource")[0]
            if (intent.extras!!.containsKey("tid")) {
                topicId = intent.extras!!.getInt("tid").toString()
            }
            if (ARouterUtils.parseParams(intent.extras!!, "tid")[0].checkNotNull()) {
                topicId = ARouterUtils.parseParams(intent.extras!!, "tid")[0]
            }
        }
        mViewModel.requestTopicDetail(topicId)
        addObserver()
        initView()
        SensorsDataManager.instance.onCreateTime()
    }

    private fun initView() {
        titles.add("最热")
        titles.add("最新")
        hotFragment = CommonDynamicFragment.newInstance(CommonDynamicFragment.DYNAMIC_TYPE_HOT, topicId)
        latestFragment = CommonDynamicFragment.newInstance(CommonDynamicFragment.DYNAMIC_TYPE_LATEST, topicId)
        fragments.add(hotFragment)
        fragments.add(latestFragment)
        val titlesArray: Array<String> = titles.toTypedArray()
        mDataBinding.stlDiscover.setViewPager(mDataBinding.vpTopicDetail, titlesArray, this, fragments)

        mDataBinding.ablTop.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { _, verticalOffset ->
            val offset = ScreenUtils.dpToPx(158) + mDataBinding.tvTopicDescription.height
            if (-verticalOffset in 0..offset) {
                mDataBinding.rlSearchTopic.visibility = View.VISIBLE
                mDataBinding.tvTopicDetailsCollectTop.visibility = View.GONE
                mDataBinding.tvTopicContentTop.visibility = View.GONE
            } else {
                mDataBinding.rlSearchTopic.visibility = View.GONE
                mDataBinding.tvTopicDetailsCollectTop.visibility = View.VISIBLE
                mDataBinding.tvTopicContentTop.visibility = View.VISIBLE
            }
        })
        mDataBinding.stlDiscover.setOnTabSelectListener(object : OnTabSelectListener {
            override fun onTabSelect(position: Int) {
                SensorsDataManager.instance.clickHotAndLatest(if (position == 0) "最热" else "最新")
            }

            override fun onTabReselect(position: Int) {
            }

        })
        GlideUtils.loadImg_avatar(this, SpUtils.getInstance().loadUserBean.data.icon, mDataBinding.civUserAvatar)

        mDataBinding.tvTopicDetailsCollectTop.setOnClickListener(this)
        mDataBinding.rlSearchTopic.setOnClickListener(this)
        mDataBinding.llGoodUsers.setOnClickListener(this)
        mDataBinding.ivTopicDetailsBack.setOnClickListener(this)
        mDataBinding.tvTopicDetailsCollect.setOnClickListener(this)
        mDataBinding.ivTopicDetailsShare.setOnClickListener(this)
        mDataBinding.llPublishDynamic.setOnClickListener(this)
        SensorsDataManager.instance.setFormPagePos("话题")
    }

    //简介
    private fun goTopicDescriptionDetail() {
        if (!DoubleClickHelper.isOnDoubleClick()) {
            val hashMap = HashMap<String, Any>()
            hashMap["content"] = mTopicDetailsBean?.desc.checkValue()
            hashMap["title"] = "# ${topicName}"
            ARouterUtils.jump(ActivityRouter.COMMUNITY.COMMUNITY_TOPIC_CONTENT_DETAIL, hashMap)
            SensorsDataManager.instance.clickTopicDes(topicName)
        }
    }

    private fun goGoodUsers() {
        if (!DoubleClickHelper.isOnDoubleClick()) {
            val hashMap = HashMap<String, Any>()
            hashMap["tid"] = topicId
            hashMap["tName"] = topicName
            ARouterUtils.jump(ActivityRouter.COMMUNITY.COMMUNITY_TOPIC_GOOD_USER, hashMap)
        }
    }

    private fun goTopicSearch() {
        if (!DoubleClickHelper.isOnDoubleClick()) {
            val hashMap = HashMap<String, Any>()
            hashMap["tName"] = topicName
            hashMap["tid"] = topicId
            ARouterUtils.jump(ActivityRouter.COMMUNITY.COMMUNITY_TOPIC_SEARCH, hashMap)
        }
    }

    private fun showShare() {
        //分享
        if (!DoubleClickHelper.isOnDoubleClick()) {
            mTopicDetailsBean?.let {
                mShowSharePop = mViewModel.showShare(topic2showShare(it), this, communityHelp)
                mViewModel.reqFriendList()
            }
        }
    }

    private fun topic2showShare(bean: TopicDetailsBean.DataBean): ShowShare2Bean {
        val userBean = SpUtils.getInstance().loadUserBean.data
        return ShowShare2Bean().apply {
            id = topicId.toLong()
            uid = userBean.id
            isFans = userBean.isFans
            headUrl = userBean.icon
            showType = Constants.DYNAMIC_TYPE_TOPIC
            name = userBean.name
            cover = bean.cover.checkValue()
            title = " # ${bean.name.checkValue()}"
            content = bean.desc
            url = Constants.TOPIC_DETAIL_SHARE_URL + id
        }
    }

    private fun requestCollect() {
        if (!hasFocus) {
            mViewModel.reqCollection(true, 7, topicId.toLong())
        } else {
            mViewModel.reqCollection(false, 7, topicId.toLong())
        }
    }

    private fun addObserver() {
        mViewModel.topicDetailLD.observe(this, androidx.lifecycle.Observer {
            it?.let {
                mTopicDetailsBean = it
                GlideUtils.loadImg_228(this, it.cover, mDataBinding.rciTopicCover)
                BannerSizeUtil.setBannerSizeValue(mDataBinding.rciTopicCover, 347, 129)
//                SpanUtils.setIcon(this, mDataBinding.tvTopicDescription, it.desc)
                mDataBinding.tvTopicDescription.setContent(it.desc)
                mDataBinding.tvTopicSummery.text = ("${it.dynamicNum}条内容·${NumberUtils.formatBigNum(it.viewNum)}浏览")
                mDataBinding.tvTopicContent.text = it.name
                mDataBinding.tvTopicContentTop.text = "# ${it.name}"
                topicName = it.name
                mDataBinding.tvTopicDetailsCollect.isSelected = it.isFocusFans
                mDataBinding.tvTopicDetailsCollectTop.isSelected = it.isFocusFans
                hasFocus = it.isFocusFans

                val dataList: MutableList<String> = ArrayList()
                for (data in it.userList) {
                    dataList.add(data.icon)
                }
                mDataBinding.avAvatars.setData(this, dataList, false)
                //是否支持发布动态
                mDataBinding.llPublishDynamic.visibility=if(it.isPublishTimeline==1)View.VISIBLE else View.GONE
            }
        })

        mViewModel.collectionLiveData.observe(this, androidx.lifecycle.Observer { it ->
            if (it) {
                hasFocus = !hasFocus
                mTopicDetailsBean?.isFocusFans = hasFocus
                mDataBinding.tvTopicDetailsCollect.isSelected = hasFocus
                mDataBinding.tvTopicDetailsCollectTop.isSelected = hasFocus
            }
        })
        //请求好友列表
        mViewModel.friendLiveData.observe(this, androidx.lifecycle.Observer {
            mShowSharePop?.setShareFriendAdapter(mViewModel.changeFriend(it))
        })
    }


    override fun onClick(v: View) {
        when (v.id) {
            R.id.iv_topic_details_back -> finish()
            R.id.rl_search_topic -> goTopicSearch()
            R.id.tv_topic_details_collect_top,
            R.id.tv_topic_details_collect -> requestCollect()
            R.id.iv_topic_details_share -> showShare()
            R.id.ll_good_users -> goGoodUsers()
            R.id.ll_publish_dynamic -> {
                communityHelp.goPublish(this)
                mTopicDetailsBean?.let {
                    EventBusUtils.postSticky(BaseConstant.loadPublishTopic(it.id.toLong(), it.name))
                }
            }
        }
    }

    override fun onDestroy() {
        mTopicDetailsBean?.let {
            if (!it.isFocusFans) EventBusUtils.sendNotify(MessageBus.msgId_topic_collection_false)
        }
        super.onDestroy()
        SensorsDataManager.instance.onDestroyTime()
        try {
            if (SensorsDataManager.instance.getBrowseTime() != 0L) {
                if (hotFragment != null && latestFragment != null)
                    SensorsDataManager.instance.browseTopicPage(mTopicDetailsBean!!.tagCategoryName, topicSource, topicName, hotFragment.getProgress(), latestFragment.getProgress())
            }
        } catch (e: Exception) {

        }

    }
}